const dayjs = require('dayjs');
const mobx = require('../../../framework/mobx/mobx_wx.js');
const { researchStore } = require('../../../store/modules/research/research.js');

Component({
	/**
	 * 使用MobX绑定行为
	 */
	behaviors: [mobx.storeBindingsBehavior],

	/**
	 * 配置MobX绑定
	 */
	storeBindings: {
		store: researchStore,
		fields: {
			graphData: 'graphData',
			nodes: 'nodes',
			links: 'links',
			isLoading: 'isLoading',
			isReady: 'isReady'
		},
		actions: {
			loadGraphData: 'loadGraphData',
			resetGraphData: 'resetGraphData'
		}
	},

	/**
	 * 组件的属性列表
	 */
	properties: {
		projectId: {
			type: String,
			value: '',
			observer: function (newVal, oldVal) {
				if (newVal && newVal !== oldVal) {
					this._init();
				}
			}
		},
		showBranch: {
			type: Boolean,
			value: true
		},
		showFlow: {
			type: Boolean,
			value: true
		}
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		width: 600,
		height: 800,
		scale: 1,
		translateX: 0,
		translateY: 0,
		isDragging: false,
		startX: 0,
		startY: 0,
		selectedNode: null,
		touchStartTime: 0,
		showDetailModal: false
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		/**
		 * 初始化
		 */
		_init() {
			if (!this.data.projectId) return;
			
			// 重置图谱数据
			this.resetGraphData();
			
			// 设置选中节点为null
			this.setData({
				selectedNode: null
			});
			
			// 加载图谱数据
			this.loadGraphData({
				projectId: this.data.projectId,
				showBranch: this.data.showBranch,
				showFlow: this.data.showFlow
			});
		},
		
		/**
		 * 计算图谱初始位置
		 */
		_calculateInitialPosition() {
			if (!this.data.nodes || this.data.nodes.length === 0) return;
			
			// 获取画布尺寸
			const query = this.createSelectorQuery();
			query.select('.graph-container').boundingClientRect(rect => {
				if (!rect) return;
				
				this.setData({
					width: rect.width,
					height: rect.height
				});
				
				// 计算图谱中心点
				let minX = Infinity, maxX = -Infinity;
				let minY = Infinity, maxY = -Infinity;
				
				this.data.nodes.forEach(node => {
					minX = Math.min(minX, node.x);
					maxX = Math.max(maxX, node.x);
					minY = Math.min(minY, node.y);
					maxY = Math.max(maxY, node.y);
				});
				
				const graphWidth = maxX - minX;
				const graphHeight = maxY - minY;
				const graphCenterX = minX + graphWidth / 2;
				const graphCenterY = minY + graphHeight / 2;
				const canvasCenterX = rect.width / 2;
				const canvasCenterY = rect.height / 2;
				
				// 计算平移量，使图谱居中
				const translateX = canvasCenterX - graphCenterX;
				const translateY = canvasCenterY - graphCenterY;
				
				// 计算缩放比例，使图谱适应画布
				const scaleX = rect.width / (graphWidth * 1.2);
				const scaleY = rect.height / (graphHeight * 1.2);
				const scale = Math.min(scaleX, scaleY);
				
				this.setData({
					translateX,
					translateY,
					scale: scale > 0 ? scale : 1
				});
			}).exec();
		},
		
		/**
		 * 手指触摸开始事件
		 * @param {Object} e 事件对象
		 */
		touchStart(e) {
			if (!this.data.isReady) return;
			
			const touch = e.touches[0];
			
			this.setData({
				isDragging: true,
				startX: touch.clientX,
				startY: touch.clientY,
				touchStartTime: dayjs().valueOf()
			});
			
			// 注释掉这部分代码，防止与onNodeTap冲突
			/* 
			// 检查是否点击了节点
			const x = (touch.clientX - this.data.translateX) / this.data.scale;
			const y = (touch.clientY - this.data.translateY) / this.data.scale;
			
			let selectedNode = null;
			for (let i = this.data.nodes.length - 1; i >= 0; i--) {
				const node = this.data.nodes[i];
				const distance = Math.sqrt(Math.pow(x - node.x, 2) + Math.pow(y - node.y, 2));
				
				if (distance <= node.size / this.data.scale) {
					selectedNode = node;
					break;
				}
			}
			
			if (selectedNode) {
				this.setData({
					selectedNode
				});
			}
			*/
		},
		
		/**
		 * 手指触摸移动事件
		 * @param {Object} e 事件对象
		 */
		touchMove(e) {
			if (!this.data.isReady || !this.data.isDragging) return;
			
			const touch = e.touches[0];
			const dx = touch.clientX - this.data.startX;
			const dy = touch.clientY - this.data.startY;
			
			// 设置最小移动距离，避免点击时的微小移动
			if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
				this.setData({
					translateX: this.data.translateX + dx,
					translateY: this.data.translateY + dy,
					startX: touch.clientX,
					startY: touch.clientY
				});
			}
		},
		
		/**
		 * 手指触摸结束事件
		 * @param {Object} e 事件对象
		 */
		touchEnd(e) {
			if (!this.data.isReady) return;
			
			// 检查是否是点击事件
			const touchEndTime = dayjs().valueOf();
			const touchDuration = touchEndTime - this.data.touchStartTime;
			
			// 仅更新拖拽状态，不要影响弹窗状态
			this.setData({
				isDragging: false
			});
			
			// 注释掉这部分，避免干扰onNodeTap
			/*
			// 如果是短时间触摸，并且有选中节点，触发点击事件
			if (touchDuration < 200 && this.data.selectedNode) {
				this._handleNodeClick(this.data.selectedNode);
			}
			*/
		},
		
		/**
		 * 处理节点点击事件
		 * @param {Object} node 节点数据
		 */
		_handleNodeClick(node) {
			// 触发节点点击事件
			this.triggerEvent('nodeClick', {
				node
			});
		},
		
		/**
		 * 双指缩放开始事件
		 * @param {Object} e 事件对象
		 */
		scaleStart(e) {
			if (!this.data.isReady || e.touches.length !== 2) return;
			
			const touch1 = e.touches[0];
			const touch2 = e.touches[1];
			const distance = Math.sqrt(
				Math.pow(touch1.clientX - touch2.clientX, 2) + 
				Math.pow(touch1.clientY - touch2.clientY, 2)
			);
			
			this.setData({
				initialDistance: distance
			});
		},
		
		/**
		 * 双指缩放移动事件
		 * @param {Object} e 事件对象
		 */
		scaleMove(e) {
			if (!this.data.isReady || e.touches.length !== 2 || !this.data.initialDistance) return;
			
			const touch1 = e.touches[0];
			const touch2 = e.touches[1];
			const distance = Math.sqrt(
				Math.pow(touch1.clientX - touch2.clientX, 2) + 
				Math.pow(touch1.clientY - touch2.clientY, 2)
			);
			
			const scale = this.data.scale * (distance / this.data.initialDistance);
			
			// 限制缩放范围
			if (scale >= 0.2 && scale <= 3) {
				this.setData({
					scale,
					initialDistance: distance
				});
			}
		},
		
		/**
		 * 重置图谱位置
		 */
		resetPosition() {
			this._calculateInitialPosition();
		},
		
		/**
		 * 节点点击处理
		 * @param {Object} e 事件对象
		 */
		onNodeTap(e) {
			// 阻止事件冒泡，防止触发图谱的拖动
			e.stopPropagation();
			
			const node = e.currentTarget.dataset.node;
			if (node) {
				console.log('节点点击：', node);
				
				// 确保touchEnd不会覆盖这里的设置
				this.setData({
					isDragging: false,
					selectedNode: node,
					showDetailModal: true
				});
				
				// 触发节点点击事件
				this.triggerEvent('nodeClick', {
					node
				});
			}
		},
		
		/**
		 * 关闭节点详情弹窗
		 */
		closeDetailModal() {
			this.setData({
				showDetailModal: false
			});
		}
	},

	/**
	 * 组件生命周期函数
	 */
	lifetimes: {
		attached() {
			// 获取系统信息设置图谱大小
			try {
				// 使用推荐的窗口信息API
				const windowInfo = wx.getWindowInfo();
				this.setData({
					width: windowInfo.windowWidth,
					height: windowInfo.windowHeight - 150
				});
			} catch (error) {
				console.warn('获取窗口信息失败，使用默认值', error);
				// 使用默认值
				this.setData({
					width: 375, // 默认值
					height: 500 // 默认值
				});
			}
			
			// 如果有项目ID，初始化图谱
			if (this.data.projectId) {
				this._init();
			}
		}
	}
}); 